#include <iostream>
#include <string>
using namespace std;

long long C(long long n1, long long n2)
{
    // n1 > n2
    long long n3 = n1 - n2;
    long long sum = 1;
    for (int i = n2; i <= n1; i++)
    {
        sum *= i;
    }
    for (int i = 2; i <= n3; i++)
    {
        sum /= i;
    }
    return sum;
}

long long timesof3(long long n)
{
    if (n == 0)
    {
        return 0;
    }
    long long sum = 1;
    for (int i = 1; i <= n; i++)
    {
        sum *= 3;
    }
    return sum;
}

int main()
{
    long long T;
    long long N;
    long long count;
    cin >> T;
    while (T--)
    {
        cin >> N;
        int weishu = to_string(N).length();
        count = 0;
        count += C(weishu, 2);
        count += timesof3(weishu - 2);
        long long minweishunumber = 1;
        for (int i = 2; i <= weishu; i++)
        {
            minweishunumber *= 10;
        }
        for (; minweishunumber <= N; minweishunumber++)
        {
            if (to_string(minweishunumber).find('3') != string::npos && to_string(minweishunumber).find('5') != string::npos)
            {
                count++;
            }
        }
        cout << count << endl;
    }
}